home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Tech Arsenal 1
/
Tech Arsenal (Arsenal Computer).ISO
/
tek-01
/
msoftapp.zip
/
SORT.CPP
< prev
next >
Wrap
C/C++ Source or Header
|
1993-06-01
|
1KB
|
64 lines
////////////////////////////////////////////////////////////////
// Sort program showing how to use qsort with C++.
//
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream.h>
//////////////////
// Your favorite class that you want to sort.
//
class Person {
char name[20];
public:
Person(const char *n) { strcpy(name, n); }
void print() { cout << name << '\n'; };
// Note that Compare function is static
static int Compare(const void* v1, const void* v2);
};
/////////////////
// Static sort function can access name since its a class member.
// But it's an ordinary function; there's no "this" pointer.
//
int Person::Compare(const void* v1, const void* v2)
{
Person *p1 = *((Person**)v1);
Person *p2 = *((Person**)v2);
return strcmp(p1->name, p2->name);
}
// Some sample people (unsorted).
Person people[] = {
{ "Cynthia" },
{ "Sandy" },
{ "Carl" },
{ "Alfred" },
{ "Beth" }
};
const NPEOPLE = sizeof(people)/sizeof(Person);
/////////////////
// Main program loop:
// create array of pointers, sort it, then print.
//
main(int, char**)
{
Person *array[NPEOPLE];
// Initialize array of pointers from sample Persons
for (int i=0; i<NPEOPLE; i++)
array[i] = &people[i];
// sort the array
qsort(array, NPEOPLE, sizeof(Person*), Person::Compare);
// print
for (i=0; i<NPEOPLE; i++)
array[i]->print();
return 0;
}